package middleware

import (
    "bytes"
    "encoding/json"
    "fmt"
    "github.com/beego/beego/v2/server/web/context"
    "io/ioutil"
    "time"
)

type RequestLoggerMiddleware struct{}

func NewRequestLoggerMiddleware() *RequestLoggerMiddleware {
    return &RequestLoggerMiddleware{}
}

func (m *RequestLoggerMiddleware) DumpRequest(ctx *context.Context) {
    startTime := time.Now()
    
    // 获取请求信息
    requestBody, _ := ioutil.ReadAll(ctx.Request.Body)
    ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))

    // 存储开始时间和请求体供后续使用
    ctx.Input.SetData("startTime", startTime)
    ctx.Input.SetData("requestBody", requestBody)

    // Print request log
    fmt.Printf("\n==== Request Received ====\n")
    fmt.Printf("Time: %v\n", startTime.Format("2006-01-02 15:04:05.000"))
    fmt.Printf("Method: %s\n", ctx.Request.Method)
    fmt.Printf("Path: %s\n", ctx.Request.URL.String())
    fmt.Printf("Remote Address: %s\n", ctx.Request.RemoteAddr)
    if len(requestBody) > 0 {
        fmt.Printf("Request Body:\n%s\n", string(requestBody))
    }
    fmt.Printf("==== Request Details End ====\n\n")
}

func (m *RequestLoggerMiddleware) DumpResponse(ctx *context.Context) {
    startTime := ctx.Input.GetData("startTime").(time.Time)
    elapsed := time.Since(startTime)

    // Get response data
    var responseBody string
    if data := ctx.Input.GetData("json"); data != nil {
        if jsonBytes, err := json.MarshalIndent(data, "", "    "); err == nil {
            responseBody = string(jsonBytes)
        }
    }

    // Print response log
    fmt.Printf("\n==== Response Sent ====\n")
    fmt.Printf("Processing Time: %v\n", elapsed)
    fmt.Printf("Status Code: %d\n", ctx.ResponseWriter.Status)
    if responseBody != "" {
        fmt.Printf("Response Body:\n%s\n", responseBody)
    }
    fmt.Printf("==== Response Details End ====\n\n")
}
